<template>
  <div class="m-iselect">
    <span class="name">按省份选择:</span>
    <el-select v-model="pvalue" placeholder="省份">
      <el-option
        v-for="item in province"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-select v-model="cvalue" :disabled="!city.length" placeholder="城市">
      <el-option
        v-for="item in city"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-autocomplete
      v-model="input"
      :fetch-suggestions="querySearchAsync"
      placeholder="请输入城市中文或拼音"
      @select="handleSelect"
    />
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      province: [],
      pvalue: "",
      city: [],
      cvalue: "",
      input: "",
      cities: []
    };
  },
  watch: {
    pvalue: async function(newPvalue) {
      let self = this;
      let { status, data } = await self.$axios.get(
        `api/ws/district/v1/getchildren?id=${newPvalue}&key=4VIBZ-5EVE4-VP4UR-DST4G-EURJT-MSB5L`
      );
      if (status === 200) {
        self.city = data.result[0].map(item => {
          return {
            value: item.id,
            label: item.fullname
          };
        });
        self.cvalue = "";
      }
    }
  },
  mounted: async function() {
    let self = this;
    let { status, data } = await self.$axios.get(
      "api/ws/district/v1/list?key=4VIBZ-5EVE4-VP4UR-DST4G-EURJT-MSB5L"
    );
    if (status === 200) {
      self.province = data.result[0].map(item => {
        return {
          value: item.id,
          label: item.fullname
        };
      });
    }
  },
  methods: {
    querySearchAsync: _.debounce(async function(query, cb) {
      let self = this;
      if (query.length) {
        if (self.cities.length) {
          cb(self.cities.filter(item => item.value.indexOf(query) > -1));
        } else {
          let { status, data } = await self.$axios.get(
            "api/ws/district/v1/search?&keyword=" +
              query +
              "&key=4VIBZ-5EVE4-VP4UR-DST4G-EURJT-MSB5L"
          );
          if (status === 200) {
            self.cities = data.result[0].map(item => {
              return {
                value: item.fullname,
                city: item.address.split(',')[1] + "市"
              };
            });
            cb(self.cities.filter(item => item.value.indexOf(query) > -1));
          } else {
            cb([]);
          }
        }
      }
    }, 200),
    handleSelect: function(item) {
      this.$store.state.geo.position.city = item.city
      this.$router.push({ path: "/"});
    }
  }
};
</script>

<style lang="scss">
@import "@/assets/css/changeCity/iselect.scss";
</style>
